<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sicau Cell Atlas</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
    <script src="{% static 'plotly-2.35.2.min.js' %}"></script>
    <!-- Other head elements -->
    <!-- 引入样式 -->
    <link rel="stylesheet" href="{% static 'vue/index.css' %}">
    <!-- 引入组件库 -->
    <script src="{% static 'vue/vue.js' %}"></script>
    <script src="{% static 'vue/index.js' %}"></script>
</head>

<body>
    <div id="app">
        <!-- 导航栏 -->
        <nav class="navbar">
            <div class="logo">
                <img src="{% static 'images/logo.png' %}" alt="BrainCellAtlas">
            </div>
            <div class="nav-links">
                <a href="#" class="nav-item">Home</a>
                <a href="#" class="nav-item active">Data Viewer</a>
                <a href="#" class="nav-item">Portrait</a>
                <a href="#" class="nav-item">Gene</a>
                <a href="#" class="nav-item">Exploration</a>
                <a href="#" class="nav-item">Dataset</a>
                <a href="#" class="nav-item">Help</a>
                <a href="#" class="nav-item">Contact</a>
            </div>
        </nav>

        <!-- 主要内容区域 -->
        <main class="container">
            <header class="header">
                <h1>Welcome to the Brain Cell Atlas</h1>
            </header>

            <!-- 选择器区域 -->
            <form id="data-form" class="form-container">
                <div class="selector-group">
                    <label for="subcluster-select">Subcluster</label>
                    <el-select v-model="selectedSubcluster" @change="render_data"
                        filterable placeholder="请选择">
                        <el-option v-for="subcluster in subclusters" :key="subcluster" :label="subcluster"
                            :value="subcluster">
                        </el-option>
                    </el-select>
                </div>

                <div class="selector-group">
                    <label for="data-name-select">Data_name</label>
                    <el-select v-model="selectedDataName" @change="render_data" filterable
                        placeholder="请选择">
                        <el-option v-for="data_name in data_names" :key="data_name" :label="data_name"
                            :value="data_name">
                        </el-option>
                    </el-select>
                </div>
            </form>

            <!-- Color By 和 Features 部分 -->
            <div class="color-features-container">
                <div class="selector-group">
                    <label for="color-select">Color By</label>
                    <el-select id="color-select" name="color" v-model="selectedCell" @change="render_data" filterable
                        placeholder="请选择">
                        <el-option v-for="cell_state in cell_states" :key="cell_state" :label="cell_state"
                            :value="cell_state">
                        </el-option>
                    </el-select>
                </div>

                <div class="selector-group">
                    <label for="features-select">Features</label>
                    <el-select v-model="selectedFeature" filterable remote reserve-keyword
                        v-el-select-loadmore="handleScroll" placeholder="input feature name"
                        @change="updatedataGene"
                        :remote-method="remoteMethod" :loading="featureLoading">
                        <el-option v-for="item in features" :key="item" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </div>
            </div>

            <!-- 图表显示区域 -->
            <div class="charts-container">
                <div id="cell-type-plot" class="plot"></div>
                <div id="features-plot" class="plot"></div>
            </div>
        </main>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        data: function () {
            return {
                subclusters: [],
                data_names: [],
                cell_states: [],
                features: [], // 存储特征选项

                scrollListener: null, // 用于存储滚动事件监听器
                selectedFeature: 'A1BG', // 存储选中的特征
                selectedSubcluster: 'ALL',
                selectedDataName: 'nature2020',
                selectedCell: null,

                cellTypeData: null,
                regionData: null,
                featuresData: null,
                layout: {
                    legend: {
                        itemclick: false,
                        itemdoubleclick: false
                    },
                },
                currentFeaturePage: 1, // 当前页码
                featurePageSize: 10, // 每页条目数
                featureSearchQuery: '', // 搜索关键字
                featureTotalPages: 0, // 总页数
                featureLoading: false // 加载状态
            }
        },
        directives: {
            'el-select-loadmore': {
                bind(el, binding) {
                    const SELECTWRAP_DOM = el.querySelector(
                        '.el-select-dropdown .el-select-dropdown__wrap'
                    )
                    SELECTWRAP_DOM.addEventListener('scroll', function (target) {
                        binding.value(target)
                    })
                }
            }
        },
        methods: {
            handleScroll(event) {
                if (!this.featureLoading) {
                    const bottom = event.target.scrollHeight === event.target.scrollTop + event.target.clientHeight;
                    if (bottom && this.currentFeaturePage < this.featureTotalPages) {
                        this.currentFeaturePage++;
                        this.fetchFeatures(); // 加载更多数据
                    }
                }
            },
            remoteMethod: async function (query) {
                if (query !== '') {
                    this.featureLoading = true; // 开始加载
                    this.currentFeaturePage = 1; // 重置页码
                    this.featureSearchQuery = query; // 更新搜索关键字
                    // 搜索重置
                    this.features = []
                    await this.fetchFeatures(); // 获取特征
                    this.featureLoading = false; // 结束加载
                } else {
                    this.features = []; // 清空特征
                }
            },
            fetchFeatures: async function () {
                const url = `/app1/get_features/?page=${this.currentFeaturePage}&page_size=${this.featurePageSize}&search=${this.featureSearchQuery}`;
                try {
                    const response = await fetch(url);
                    const data = await response.json();
                    data.features.forEach(feature => {
                        this.features.push(feature);
                    });
                    this.featureTotalPages = data.totalPages; // 更新总页数
                } catch (error) {
                    console.error('Error fetching features:', error);
                }
            },
            fetchData: function () {
                const url = `/app1/get_data/?subcluster=${this.selectedSubcluster}&gene=${this.selectedFeature}&data_name=${this.selectedDataName}`;
                return fetch(url)
                    .then(response => response.json())
                    .then(responseData => {
                        // Assign response data to Vue data properties
                        [this.cellTypeData, this.regionData, this.featuresData] = responseData; // Destructure responseData
                    })
                    .catch(error => console.error('Error fetching data:', error));
            },
            render_data: function () {
                this.fetchData().then(() => {
                    // 清除旧的图表
                    Plotly.purge(document.getElementById("cell-type-plot"));
                    Plotly.purge(document.getElementById("features-plot"));
                    Plotly.newPlot("cell-type-plot", this.cellTypeData, this.layout);
                    Plotly.newPlot("features-plot", this.featuresData, this.layout);
                    // 添加图例点击事件处理
                    this.handleLegendClick(document.getElementById("cell-type-plot"), this.cellTypeData);
                })
                    .catch(error => console.error('Error:', error));
            },
            handleLegendClick: function (container, data) {
                container.on("plotly_legendclick", (event) => {
                    const opacity_list = data.map(item => item['opacity']);
                    const seq_list = data.map((_, index) => index);
                    const curveNumber = event.curveNumber;

                    const update = { opacity: opacity_list[curveNumber] === 1 ? 0.3 : 1 };
                    const res_list = seq_list.filter(item => item !== curveNumber);
                    Plotly.restyle(container.id, update, res_list);
                });
            },
            updatedata: function () {
                Plotly.purge(document.getElementById("cell-type-plot"));
                const data = this.colorSelector === 'cell_states' ? this.cellTypeData : this.regionData;
                Plotly.newPlot("cell-type-plot", data, this.layout);
                this.handleLegendClick(document.getElementById("cell-type-plot"), data);
            },
            updatedataGene: function () {
                this.fetchData()
                    .then(() => {
                        Plotly.purge(document.getElementById("features-plot"));
                        Plotly.newPlot("features-plot", this.featuresData, this.layout);
                    })
                    .catch(error => console.error('Error:', error));
            }
        },
        mounted() {
            this.subclusters = {{ subclusters | safe }}
            this.data_names = {{ data_names | safe }}
            this.cell_states = {{ cell_states | safe }}
            this.fetchFeatures();
    // 初始化渲染
            this.render_data();
        },
    });
</script>

</html>